import com.lefu.utils.common.excelhelper.ExcelRead;
import org.apache.commons.lang.StringUtils;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

/**
 * Created by lrs on 2018/2/25.
 */
public class Img {
    /**
     * 读取断点文件
     * @return
     * @throws java.io.IOException
     */
    private String[] readBreakpoint() throws IOException {
        InputStreamReader reader = new InputStreamReader(new FileInputStream("./output/breakpoint")); // 建立一个输入流对象reader
        BufferedReader br = new BufferedReader(reader); // 建立一个对象，它把文件内容转成计算机能读懂的语言
        String line = "";
        line = br.readLine();
        br.close();
        reader.close();
        if (!StringUtils.isEmpty(line)) {
            return line.split(",");
        } else {
            return null;
        }
    }

    /**
     * 下载文件并保存
     * @param urlString
     * @param filename
     * @param savePath
     * @throws Exception
     */
    private void download(String urlString, String filename, String savePath) throws IOException {
        URL url = new URL((urlString)); // 构造URL
        URLConnection con = url.openConnection(); // 打开连接
        // con.setConnectTimeout(5 * 1000); //设置请求超时为5s
        InputStream is = con.getInputStream(); // 输入流
        byte[] bs = new byte[4096]; // 1K的数据缓冲
        int len; // 读取到的数据长度
        File sf = new File(savePath); // 输出的文件流
        if (!sf.exists()) {
            sf.mkdirs();
        }
        OutputStream os = new FileOutputStream(sf.getPath() + "\\" + filename);

        // 开始读取
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }

        // 完毕，关闭所有链接
        os.close();
        is.close();
    }


    /**
     * 下载产品信息中的所有图片
     * @throws Exception
     */
    public void downloadImg() throws Exception {
        // 读取断点文件，并且计算上一次失败位置
        String[] breakpoint = readBreakpoint();

        int breakRow = 0;
        if (null == breakpoint) {
            breakRow = 0;
        } else if (breakpoint[0].equals("DownloadImg")) {
            breakRow = Integer.parseInt(breakpoint[1]);
        } else {
            return;
        }

        System.out.println("========================================");
        System.out.println("开始下载图片");

        File file = new File("./output/Product.xls");
        FileInputStream fis = new FileInputStream(file);
        ExcelRead excelReader = new ExcelRead(fis);

        if (breakRow != 0) {
            excelReader.setBodyRow(breakRow - 1);
        }

        FileHelp fileHelp = new FileHelp();
        while (excelReader.next()) {
            fileHelp.writeFile("./output/breakpoint", "DownloadImg," + excelReader.getCurrentRow());

            System.out.println(excelReader.getString("轮播图URL"));

            for (String url : excelReader.getString("轮播图URL").split("\\|")) {
                if (!StringUtils.isEmpty(url)) {
                    String imgName = "";
                    String[] names = url.split("/");
                    if (names.length >= 1) {
                        imgName = names[names.length - 1];
                    }

                    if (StringUtils.isEmpty(imgName)) {
                        System.out.println("::::::::::::::: 下载图片错误 url:" + url + " 拆取图片名错误（名称为空）");
                    } else {
                        try {
                            // url编码
                            url = url.replace(imgName, URLEncoder.encode(imgName,"UTF-8"));
                            url = url.replaceAll("\\+","%20");

                            download(url, imgName, "./output/img"); // 下载图片
                        } catch (FileNotFoundException e) {
                            System.out.println("::::::::::::::: 下载图片失败（404）url:" + e.getMessage());
                        } catch (IOException e) {
                            System.out.println("::::::::::::::: 下载图片失败 IOException url:" + e.getMessage());
                        }
                    }
                }
            }
        }

        System.out.println("下载图片完成！！！");
    }

}
